﻿using System;
using System.Web.UI;
using Blazing.WebFacade;
using System.Web.Configuration;
using Blazing.Web.Controls;
using Blazing.BusinessObjects.Cms;
using System.Web.UI.WebControls;
using Blazing.Web.Util;

namespace Blazing.WebShop.Classes
{
    public class SiteBasePage : Page
    {
        protected internal CmsManager _manager;
        protected internal Contentpage _page = null;
        protected internal Site _site = null;

        public CmsManager CmsContent
        {
            get { return _manager; }
        }

        public virtual string PagePath
        {
            get
            {
                return Request.QueryString["path"];
            }
        }

        public void InvalidateOutputcache()
        {
            if (_page != null)
                Cache.Remove(string.Format("Page_{0}", _page.ID));
        }

        public void GenerateCacheDependency()
        {
            if (_page != null)
                Response.AddCacheItemDependency(string.Format("Page_{0}", _page.ID));
        }

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);

            string hostUrl = Request.Url.Host;

            //if test app
            if (WebConfigurationManager.AppSettings["TestMode"] == "True")
                hostUrl = WebConfigurationManager.AppSettings["TestSite"];

            SiteController siteCon = new SiteController();
            _site = siteCon.GetSite(hostUrl);
            string requestUrl = "";
            if (_site != null)
            {
                requestUrl = PagePath; //Request.Url.AbsolutePath.Replace("Control.aspx", "");
                requestUrl = requestUrl == null ? string.Empty : requestUrl;
                requestUrl = string.Format("{0}{1}", requestUrl.StartsWith("/") ? "" : "/", requestUrl);
                requestUrl = string.Format("{0}{1}", requestUrl, requestUrl.EndsWith("/") ? "" : "/");

                PageController pageCon = new PageController();
                _page = pageCon.GetPage(_site.ID, requestUrl);
            }

            //check for redirects here...

            if (_page == null && !PagePath.Contains("/404"))
            {
                Response.Redirect(string.Format("{0}/404/", requestUrl), false);
                Response.StatusCode = 301;
                Response.End();
            }
            else if (_page != null)
            {
                MasterPageFile = _page.Masterpage.Path;
                Theme = _page.Theme.Path;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            _manager = Blazing.Util.CmsManagerHelper.FindManagerObject(Controls);
            CmsContent.PageId = _page.ID;
            CmsContent.SiteId = _site.ID;

            Title = _page.PageTitle;

            if (!string.IsNullOrEmpty(_page.MetaDescription))
            {
                System.Web.UI.HtmlControls.HtmlMeta ctrl = new System.Web.UI.HtmlControls.HtmlMeta();
                ctrl.Name = "description";
                ctrl.Content = _page.MetaDescription;
                Header.Controls.Add(ctrl);
            }

            if (!string.IsNullOrEmpty(_page.MetaKeywords))
            {
                System.Web.UI.HtmlControls.HtmlMeta ctrl = new System.Web.UI.HtmlControls.HtmlMeta();
                ctrl.Name = "keywords";
                ctrl.Content = _page.MetaKeywords;
                Header.Controls.Add(ctrl);
            }

            base.OnLoad(e);
        }

        //protected override object LoadPageStateFromPersistenceMedium()
        //{
        //    return ViewstateCompressionHelper.LoadPageStateFromPersistenceMedium(this);
        //}

        //protected override void SavePageStateToPersistenceMedium(object viewState)
        //{
        //    ViewstateCompressionHelper.SavePageStateToPersistenceMedium(this, viewState);
        //}

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            try
            {
                Page.Form.Controls.Add(new Literal { Text = "<!-- Queries: " + Blazing.WebFacade.Logging.CountQueriesAppender.CurrentQueryCount + " -->" });
            }
            catch { /*this is only debug information anyway*/ }

            //GenerateCacheDependency();
        }
    }
}
